<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j component-add-specifications">
    <view
      class="mask"
      @tap="cancal"
    />
    <view class="content-box">
      <view class="title">
        <text>{{ header }}</text>
        <view
          class="close"
          @tap="cancal"
        />
      </view>
      <search-bar
        v-if="addTitle === 'name'"
        class="search-bar"
        :key-wrod="specificationsName"
        :placeholder="createConfig.placeholder"
        @handle-search="handleSearch"
      />
      <view class="sku-list">
        <empty-tips
          v-if="addDataList.length === 0"
          :tips-list="tipsList"
        />
        <view
          v-for="(item, index) in addDataList"
          :key="index"
          class="sku-list-item"
          @tap="clickSkuName(item, index)"
        >
          {{ item.name }}
          <radio
            v-if="addTitle === 'value'"
            class="item-radio"
            :checked="item.isSelect"
            color="#082ba6"
            @tap="clickSkuName(item, index)"
          />
        </view>
      </view>
      <view class="add-specifications-footer">
        <common-btn
          v-if="addTitle === 'name'"
          :btn-config="prodManaBtnConfig"
          @handle-click-btn="AddSpecificationName"
        />
        <common-btn
          v-else
          :btn-config="prodManaBtnConfig"
          @handle-click-btn="AddSpecificationName"
          @handle-click-more-btn="handleClickMoreBtn"
          @select-all-btn="selectAllBtn"
        />
      </view>
    </view>
    <create-popup
      v-if="showCreatePopup"
      :reg-tip="addTitle === 'value' ? regTipVal : regTip"
      :input-val="createSkuName"
      :is-required="true"
      :config="createConfig"
      @cancal="closeCreatePopup"
      @submit="getSubmitData"
    />
  </view>
</template>

<script setup>
import createPopup from '@/package-prod/components/create-popup/create-popup.vue'
import { onMounted, reactive, watch } from 'vue'

const emit = defineEmits(['cancal', 'search'])

const props = defineProps({
  // 类型（name, value）
  addTitle: {
    type: String,
    default: 'name'
  },
  // 显示数据
  dataList: {
    type: Array,
    default: function () {
      return []
    }
  },
  // 已有数据
  allData: {
    type: Array,
    default: function () {
      return []
    }
  },
  // 当前所有skuName
  specName: {
    type: Array,
    default: function () {
      return []
    }
  }
})

const tipsList = ['您还没有添加规格']

const Data = reactive({
  specificationsName: '', // 搜索内容
  showCreatePopup: false, // 显示新增组件
  createSkuName: '', // 新增规格名/值

  createConfig: {
    header: '新建规格',
    placeholder: '请输入规格名称',
    cancalText: '取消',
    submitText: '新建并选择',
    submitTip: '请输入规格名称',
    maxlength: 10
  },
  prodManaBtnConfig: {
    btnText: '新建规格',
    isPlain: false
  },
  regTip: {
    reg: /^.*[:|;|：|；].*$/,
    regTip: '请勿输入符号“;”和“:”'
  },
  regTipVal: {
    reg: /^.*[;|；].*$/,
    regTip: '请勿输入符号“;”'
  },

  header: '添加规格名',
  addDataList: [], // 可选数据
  selList: [] // 已选数据
})

const { specificationsName, showCreatePopup, createSkuName, createConfig, prodManaBtnConfig, regTip, regTipVal, header, addDataList } = toRefs(Data)

watch(() => props.dataList, () => {
  Data.addDataList = props.dataList
})

onMounted(() => {
  Data.addDataList = props.dataList
  if (props.addTitle === 'value') {
    specValueTip()
    isSelectList()
  }
})

// 关闭
const cancal = () => {
  emit('cancal', '')
}

// 更改组件tip
const specValueTip = () => {
  if (props.addTitle === 'value') {
    Data.placeholder = '请输入规格值名称'
    Data.header = '添加规格值'
    Data.createConfig = {
      header: '新建规格值',
      placeholder: '请输入规格值名称',
      cancalText: '取消',
      submitText: '新建并选择',
      submitTip: '请输入规格值名称',
      maxlength: 20
    }
  }
}

// 搜索框事件
const handleSearch = (val) => {
  emit('search', val)
  Data.specificationsName = val
}

// 进入新增组件
const AddSpecificationName = () => {
  Data.showCreatePopup = true
}

// 底部按钮（新增、确定）
const handleClickMoreBtn = (index) => {
  switch (index) {
    case 1:
      AddSpecificationName()
      break
    case 2:
      submitBtn()
      break
  }
}

// 确定保存
const submitBtn = () => {
  emit('cancal', Data.selList)
}

// 关闭新增组件
const closeCreatePopup = () => {
  Data.showCreatePopup = false
}

// 底部按钮动态修改
const isSelectList = () => {
  // 处理浅拷贝引发的问题
  const list = JSON.parse(JSON.stringify(Data.addDataList)).filter((item) => {
    return item.isSelect
  })
  const isSelect = list.length === Data.addDataList.length
  Data.selList = list
  if (Data.addDataList.length > 0) {
    Data.prodManaBtnConfig = {
      isPlain: true,
      isSelect: true,
      btnText: '新建规格值',
      isChecked: isSelect,
      btnList: [
        {
          btnText: '新建规格值',
          isPlain: false
        },
        {
          btnText: '确定',
          isPlain: false
        }
      ]
    }
  } else {
    Data.prodManaBtnConfig = {
      btnText: '新建规格',
      isPlain: false
    }
  }
}

// 新建弹框确定
const getSubmitData = (data) => {
  Data.createSkuName = ''
  if (props.addTitle === 'name') {
    const nNameList = Array.from(new Set([...props.allData, ...Data.addDataList.map(x => x.name), ...props.specName]))
    if (nNameList.indexOf(data.toString()) > -1) {
      uni.showToast({
        title: `规格名'${data}'已存在`,
        mask: true,
        icon: 'none',
        duration: 1500
      })
      return
    }
    closeCreatePopup()
    emit('cancal', { name: data, prodPropValues: [] })
  } else {
    const vNameList = Data.addDataList.map((item) => {
      return item.name
    })
    if (vNameList.indexOf(data.toString()) > -1) {
      uni.showToast({
        title: `规格值'${data}'已存在`,
        mask: true,
        icon: 'none',
        duration: 1500
      })
      return
    }
    closeCreatePopup()
    const item = {
      propId: '',
      propValue: data,
      propValueEn: '',
      valueId: '',
      pic: '',
      name: data,
      isSelect: true
    }
    Data.addDataList.push(item)
    Data.selList.push(item)
    isSelectList()
  }
}

// 点击规格值/名
const clickSkuName = (item, num) => {
  if (props.addTitle === 'name') {
    closeCreatePopup()
    emit('cancal', item)
  } else {
    item.isSelect = !item.isSelect
    if (item.isSelect) {
      Data.addDataList[num] = item
      Data.selList.push(item)
    } else {
      Data.addDataList[num] = item
      Data.selList.splice(Data.selList.indexOf(item), 1)
    }
    isSelectList()
    if (Data.selList.length === Data.addDataList.length) {
      Data.prodManaBtnConfig.isChecked = true
    } else {
      Data.prodManaBtnConfig.isChecked = false
    }
  }
}

// 全选按钮
const selectAllBtn = (val) => {
  const list = Data.addDataList
  if (val) {
    // 处理浅拷贝引发的问题
    Data.selList = JSON.parse(JSON.stringify(Data.addDataList))
    // eslint-disable-next-line no-unused-vars
    list.forEach((item, index) => {
      list[index].isSelect = true
    })
  } else {
    Data.selList = []
    // eslint-disable-next-line no-unused-vars
    list.forEach((item, index) => {
      list[index].isSelect = false
    })
  }
  Data.addDataList = list
}
</script>

<style lang="scss" scoped>
.component-add-specifications {
  @keyframes window-open {
    0% {
      bottom: -900rpx;
    }

    100% {
      bottom: 0;
    }
  }

  .content-box {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #ffffff;
    height: 60%;
    box-sizing: border-box;
    padding: 30rpx;
    border-radius: 20rpx 20rpx 0px 0px;
    animation: window-open 0.3s 1;
    padding-bottom: 114rpx;
    box-sizing: border-box;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #000000;
      // display: flex;
      // justify-content: center;
      text-align: center;
      margin-bottom: 28rpx;

      .close {
        content: '';
        width: 36rpx;
        height: 36rpx;
        background: #f5f5f5;
        border-radius: 50%;
        float: right;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .close::after {
        content: '';
        display: block;
        width: 14rpx;
        height: 14rpx;
        background: url(@/static/images/close.png) no-repeat;
        background-size: 14rpx 14rpx;
      }
    }

    .search-bar {
      margin-bottom: 34rpx;
    }

    .sku-list {
      height: 80%;
      margin-top: 20rpx;
      overflow-y: auto;

      .sku-list-item {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 46rpx;
        padding: 0 1rem;

        .item-radio {
          float: right;
        }
      }
    }
  }

  .add-specifications-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #ffffff;
    height: 114rpx;
  }
}
</style>
